CURRENT_DIR := $(shell pwd)
SOURCE_DIR := $(CURRENT_DIR)/pkg
JS_FILE := $(CURRENT_DIR)/pkg/blk1010_wasm.js
TARGET_DIR := /Users/jiajianxiao/tuyoo/cli_arc8/preview-template
build:
	wasm-pack build --target web
to_web:
	rm -rf $(TARGET_DIR)/$(notdir $(SOURCE_DIR))
	@echo "Copying $(SOURCE_DIR) to $(TARGET_DIR)..."
	cp -r $(SOURCE_DIR) $(TARGET_DIR)
	@echo "Copy complete."
build_web: build to_web

build_wechat:build remove_improt_meta delete_last_two_lines append_code_snippet
remove_improt_meta:
	@echo "Removing block from $(JS_FILE)..."
	@sed -i '' 's/input = new URL('\''blk1010_wasm_bg.wasm'\'', import.meta.url);/\/\/&/'  $(JS_FILE)
	@echo "Block removed."
delete_last_two_lines:
	@echo "Deleting last two lines of $(JS_FILE)..."
	@sed '$$d' $(JS_FILE) > temp_file && mv temp_file $(JS_FILE)
	@sed '$$d' $(JS_FILE) > temp_file && mv temp_file $(JS_FILE)
	@echo "Deletion complete."
append_code_snippet:
	@echo "Appending code snippet to $(JS_FILE)..."
	@echo "async function initAsync() {" >> $(JS_FILE)
	@echo "    if (wasm !== undefined) return wasm;" >> $(JS_FILE)
	@echo "    const imports = __wbg_get_imports();" >> $(JS_FILE)
	@echo "    __wbg_init_memory(imports);" >> $(JS_FILE)
	@echo "    try {" >> $(JS_FILE)
	@echo "        const results = await WXWebAssembly.instantiate(\"wasm/blk1010_wasm_bg.wasm\", imports);" >> $(JS_FILE)
	@echo "        const instance = results.instance;" >> $(JS_FILE)
	@echo "        const module = results.module;" >> $(JS_FILE)
	@echo "        return __wbg_finalize_init(instance, module);" >> $(JS_FILE)
	@echo "    } catch (error) {" >> $(JS_FILE)
	@echo "        // Handle error" >> $(JS_FILE)
	@echo "        console.error(\"Error initializing wasm:\", error);" >> $(JS_FILE)
	@echo "        throw error;" >> $(JS_FILE)
	@echo "    }" >> $(JS_FILE)
	@echo "}" >> $(JS_FILE)
	@echo "export { initSync, initAsync, __wbg_init }" >> $(JS_FILE)
	@echo "Code snippet appended."
to_wehcat:
	cp -f $(CURRENT_DIR)/pkg/blk1010_wasm_bg.wasm /Users/jiajianxiao/tuyoo/cli_arc8/build-templates/wechatgame/wasm/blk1010_wasm_bg.wasm
	cp -f $(CURRENT_DIR)/pkg/blk1010_wasm.js /Users/jiajianxiao/tuyoo/cli_arc8/build-templates/wechatgame/blk1010_wasm.js